package com.ks.app.navigate.action;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import javax.annotation.Resource;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import com.ks.app.admin.action.BaseAction;
import com.ks.app.admin.util.Pager;
import com.ks.app.navigate.hibernate.KsNavigate;
import com.ks.app.navigate.hibernate.KsWebsite;
import com.ks.app.navigate.service.KsNavigateService;
import com.ks.app.navigate.service.KsWebsiteService;
import com.ks.app.navigate.util.JsoupUtil;
import com.ks.app.search.util.Constants;

@ParentPackage("struts-default")
@InterceptorRefs( {
	@InterceptorRef("defaultStack"),
	@InterceptorRef(value = "fileUpload", params = {"allowedTypes","image/jpeg,image/gif,image/png","maximumSize", "97867700" })
})   

@Results( {
	@Result(name = "editweb", location = "/WEB-INF/website/editwebsite.jsp"),
	@Result(name = "listweb", location = "/WEB-INF/website/listwebsite.jsp"),
	@Result(name = "website", location = "/WEB-INF/website/navigate_website.jsp")
})
public class KsWebsiteAction extends BaseAction {
	
	private static final long serialVersionUID = 1L;
	private Log log = LogFactory.getLog(this.getClass());
	
	@Resource(name="ksWebsiteService")
	private KsWebsiteService webService;
	
	@Resource(name="ksNavigateService")
	private KsNavigateService navService;
	
	private File logopic;
	private String logopicFileName;
	

	/**
	 * 客户端-----获取某导航条下站点
	 * @return
	 */
	@Action(value="ks_navigate_website")
	public String findWebsite(){
		
		long    navigateid =  request.getParameter("nid")==null?0l:Long.parseLong(request.getParameter("nid"));
		List<KsWebsite> list = webService.findKsWebsiteList(navigateid);
		KsNavigate nav = navService.findKsNavigateById(navigateid);
		request.setAttribute("weblist", list);
		request.setAttribute("navi", nav.getName());
		return "website";
	}

	
	/**
	 * 站点页面
	 * @return
	 */
	@Action(value="edit_web")
	public String editwebsite(){
		
		long  id =  request.getParameter("id")==null?0l:Long.parseLong(request.getParameter("id"));
		int pno  = request.getParameter("pno")==null?1:Integer.parseInt(request.getParameter("pno"));
		
		String name    = request.getParameter("name")     == null?"":request.getParameter("name").trim();
		int  status    = request.getParameter("status")   == null?0:Integer.parseInt(request.getParameter("status"));
		int  recommend    = request.getParameter("recommend")   == null?0:Integer.parseInt(request.getParameter("recommend"));
		long navigateid  = (request.getParameter("navigateid") == null || "".equals(request.getParameter("navigateid")))?-1l:Long.parseLong(request.getParameter("navigateid"));
		
		if(id != 0){
			KsWebsite web = webService.findKsWebsiteById(id);
			request.setAttribute("website", web);
		}
		
		
		List<KsNavigate> list = navService.findLeafKsNavigate();
		request.setAttribute("navlist", list);
		request.setAttribute("pno", pno);
		request.setAttribute("name", name);
		request.setAttribute("status", status);
		request.setAttribute("recommend", recommend);
		request.setAttribute("navigateid", navigateid);
		
		return "editweb";
	}
	
	/**
	 * 新增或修改站点
	 * @return
	 */
	@Action(value="ks_add_website")
	public String addWebsite(){
		
		String logodir = Constants.CONS_PROPERTIES.getValue("filedir")+"/logo/";
			//ServletActionContext.getServletContext().getRealPath("/upload/logo/");
			
		try {
			
		    long          id   =  request.getParameter("wid")==null?0l:Long.parseLong(request.getParameter("wid"));
			long    navigateid =  request.getParameter("wnavigateid")==null?0l:Long.parseLong(request.getParameter("wnavigateid"));
			String     name    =  request.getParameter("wname")==null?"":request.getParameter("wname");
			String      url    =  request.getParameter("wurl")==null?"":request.getParameter("wurl");
			int   status       =  request.getParameter("wstatus")==null?1:Integer.parseInt(request.getParameter("wstatus"));
			int   recommend    =  request.getParameter("wrecommend")==null?1:Integer.parseInt(request.getParameter("wrecommend"));
			int   ordernum     =  request.getParameter("wordernum")==null?1:Integer.parseInt(request.getParameter("wordernum"));
			
			String logoname    ="";
			String logopath    ="";
			if(getLogopic()!=null){
				logoname      = generateFileName(logopicFileName);
				logopath      = logodir+logoname;
				File targeta  = new File(logodir+"/",logoname);
				FileUtils.copyFile(logopic, targeta);
			}
			
			KsWebsite website = null;
			if(id != 0){
				
				website = webService.findKsWebsiteById(id);
				website.setLogo(logopath);
				website.setName(name);
				website.setNavigateid(navigateid);
				website.setRecommend(recommend);
				website.setStatus(status);
				website.setUrl(url);
				website.setOrdernum(ordernum);
				
			}else {
				website = new KsWebsite( navigateid,  name,  url,  status,  recommend,logopath,ordernum);
			}
			webService.saveKsWebsite(website);
		
		} catch (Exception e) {
			log.info(e.getMessage());
			e.printStackTrace();	
		}
		
		return findWebsiteList();
	}

	/**
	 * 删除web站点
	 * @return
	 */
	@Action(value="ks_del_website")
	public String delWebsite(){
		
		String usrname = String.valueOf(request.getSession().getAttribute("userinfo"));
		
		String  webids =  request.getParameter("id")==null?"":request.getParameter("id");
		webService.deleKsWebsites(webids, usrname);
		return findWebsiteList();
	}
	
	/**
	 * 站点列表
	 * @return
	 */
	@Action(value="ks_website_grid")
	public String findWebsiteList(){
		
		int  pno       = request.getParameter("pno")      == null?1:Integer.parseInt(request.getParameter("pno"));
		int  status    = request.getParameter("status")   == null?0:Integer.parseInt(request.getParameter("status"));
		int  recommend    = request.getParameter("recommend")   == null?0:Integer.parseInt(request.getParameter("recommend"));
		long navigateid  = (request.getParameter("navigateid") == null || "".equals(request.getParameter("navigateid")))?-1l:Long.parseLong(request.getParameter("navigateid"));
		String name    = request.getParameter("name")     == null?"":request.getParameter("name").trim();
		
		KsWebsite w = new KsWebsite();
		w.setName(name);
		w.setNavigateid(navigateid);
		w.setStatus(status);
		
		Pager pager = new Pager();
		pager.setCntOfPage(20);
		pager.setCurPage(pno);
		
		List<KsWebsite> list = webService.findKsWebsiteList(name,navigateid, status, recommend,pager);
		
		if(pno>1 && (list==null || list.size()==0)){
			
			pager.setCurPage(pno-1);
			list = webService.findKsWebsiteList(name, navigateid, status,recommend, pager);
			
		}else if(pno==1 && (list==null || list.size()==0)){
			pager.setCurPage(0);
		}
		
		List<KsNavigate> navlist = navService.findLeafKsNavigate();
		
		request.setAttribute("list", list);
		request.setAttribute("PAGER", pager);
		request.setAttribute("navlist", navlist);
		request.setAttribute("website", w);
		
		return "listweb";
	}



	/**
	 * 生成文件名
	 * @param fileName
	 * @return
	 */
	private String generateFileName(String fileName) {
		
		DateFormat format = new SimpleDateFormat("yyMMddHHmmss");
		String formatDate = format.format(new Date());
		int random = new Random().nextInt(10000);
		int position = fileName.lastIndexOf(".");
		String extension = fileName.substring(position);

		return formatDate + random + extension;
	}
	
	
	@Action(value="initwebsite")
	public String initWebsite(){
		
		List<KsNavigate> list = navService.findValidKsNavigate();
		
		for(KsNavigate n : list){
			if(n.getParentid() !=0){
				List<KsWebsite> wlist = JsoupUtil.crawlWebsite(n.getUrl(), n.getId());
				for(KsWebsite w : wlist){
					webService.saveKsWebsite(w);
				}
			}
		}
		
		
		return null;
	}

	public File getLogopic() {
		return logopic;
	}

	public void setLogopic(File logopic) {
		this.logopic = logopic;
	}

	public String getLogopicFileName() {
		return logopicFileName;
	}

	public void setLogopicFileName(String logopicFileName) {
		this.logopicFileName = logopicFileName;
	}
	

	
}
